package cn.tedu.rms.user.service.impl;

import cn.tedu.rms.base.exception.ServiceException;
import cn.tedu.rms.base.response.StatusCode;
import cn.tedu.rms.user.mapper.UserMapper;
import cn.tedu.rms.user.pojo.dto.UserLoginParam;
import cn.tedu.rms.user.pojo.dto.UserQuery;
import cn.tedu.rms.user.pojo.dto.UserSaveParam;
import cn.tedu.rms.user.pojo.entity.User;
import cn.tedu.rms.user.pojo.vo.UserVO;
import cn.tedu.rms.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录业务,userLoginParam:{}",userLoginParam);
        UserVO userVO=userMapper.selectByUsername(userLoginParam.getUsername());
        // 判断用户名是否正确
        if (userVO==null){
            // 用户名错误
            log.debug("用户名错误");
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())){
            // 密码错误
            log.debug("密码错误");
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        log.debug("查询用户业务,userQuery:{}",userQuery);
        List<UserVO> list=userMapper.selectUser(userQuery);
        return list;
    }

    @Override
    public void save(UserSaveParam userSaveParam) {
        log.debug("保存用户业务,userSaveParam:{}",userSaveParam);
        User user=new User();
        BeanUtils.copyProperties(userSaveParam,user);
        // 判断是否是新增还是修改
        if (user.getId()==null){
            log.debug("新增用户业务");
            user.setPassword("123456");
            user.setCreateTime(new Date());
            userMapper.insert(user);
        }else {
            log.debug("修改用户业务");
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
    }

    @Override
    public void resetPassword(Long userId) {
        log.debug("重置密码业务,userId:{}",userId);
        User user=new User();
        user.setId(userId);
        // 重置密码为基础密码
        user.setPassword("123456");
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void updateStatus(Long userId, String status) {
        log.debug("修改用户状态业务,userId:{},status:{}",userId,status);
        User user=new User();
        user.setId(userId);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void deleteUser(Long userId) {
        log.debug("删除用户业务,userId:{}",userId);
        userMapper.deleteUserById(userId);
    }
}
